package Overseas

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"os"

	"../ProtoGo"
	"../Robot"
	"github.com/golang/protobuf/proto"
)

var command = Cmd.Command_SCENE_OVERSEAS_PROTOCMD.Enum()

func RegisterOverseasHandler(r *Robot.Robot) {
	cc := Cmd.Command_SCENE_OVERSEAS_PROTOCMD.Enum()
	r.RobotLog("注册overseas模块")
	r.Handler.SetModuleBegin(int32(*cc), RequestPolicy)

	pp := Cmd.OverseasSceneParam_OVERSEAS_PHOTO_UPLOAD_CMD.Enum()
	r.Handler.RegisterHandle(byte(*cc), byte(*pp), handleOverseasPhotoUploadCmd)
}

//获取上传Policy参数
func RequestPolicy(robot *Robot.Robot) {
	param := Cmd.OverseasSceneParam_OVERSEAS_PHOTO_UPLOAD_CMD.Enum()

	req := &Cmd.OverseasPhotoUploadCmd{}
	req.Cmd = command
	req.Param = param
	req.Type = Cmd.OverseasPhotoGalleryType_ENUM_GALLERY_TYPE_GUILDICON.Enum()
	req.PhotoId = proto.Uint32(9)
	robot.SendProto(byte(*command), byte(*param), req, true)
}

func handleOverseasPhotoUploadCmd(xcmd *Robot.XCommand, robot *Robot.Robot) {
	response := &Cmd.OverseasPhotoUploadCmd{}
	if err := proto.Unmarshal(xcmd.Probuf, response); err != nil {
		robot.RobotErr("序列化OverseasPhotoUploadCmd")
	} else {
		robot.RobotLog(response.String())
	}

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	writer.SetBoundary("------WebKitFormBoundary7MA4YWxkTrZu0gW")
	for i := 0; i < len(response.Fields); i++ {
		writer.WriteField(response.Fields[i].GetName(), response.Fields[i].GetValue())
	}

	fileWriter, _ := writer.CreateFormFile("file", response.GetPath())
	fh, _ := os.Open("test.png")
	io.Copy(fileWriter, fh)

	fh.Close()

	writer.Close()
	resp, _ := http.Post("https://storage.googleapis.com/ro-tw-gcs", writer.FormDataContentType(), body)
	robot.RobotLog("response = ", resp)

	//结束模块
	robot.Handler.FinishModule(int32(*command))
}
